package com.team9.fitness.controller;

import com.team9.fitness.service.ZRDDSManagerService;
import com.team9.fitness.service.ZRDDSDataExchangeService;
import com.team9.fitness.service.CallbackRegistryService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * ZRDDS控制器
 * 提供ZRDDS中间件相关的API接口
 * 使用真实的ZRDDS中间件，不使用模拟实现
 */
@RestController
@RequestMapping("/api/zrdds")
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
public class ZRDDSController {

    private static final Logger log = LoggerFactory.getLogger(ZRDDSController.class);

    @Autowired
    private ZRDDSManagerService zrddsManagerService;

    @Autowired
    private ZRDDSDataExchangeService zrddsDataExchangeService;

    @Autowired
    private CallbackRegistryService callbackRegistryService;

    /**
     * 获取ZRDDS状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getZRDDSStatus() {
        Map<String, Object> response = new HashMap<>();

        try {
            boolean initialized = zrddsManagerService.isInitialized();
            Set<String> subscribedTopics = zrddsManagerService.getSubscribedTopics();
            int messageCount = zrddsDataExchangeService.getMessageCount();

            response.put("success", true);
            response.put("initialized", initialized);
            response.put("subscribedTopics", subscribedTopics);
            response.put("messageCount", messageCount);
            response.put("zrddsVersion", "真实ZRDDS中间件");
            response.put("status", initialized ? "运行中" : "未初始化");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取ZRDDS状态失败", e);
            response.put("success", false);
            response.put("message", "获取状态失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取回调注册服务状态
     */
    @GetMapping("/callback-status")
    public ResponseEntity<Map<String, Object>> getCallbackStatus() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("callbackCount", callbackRegistryService.getCallbackCount());
        response.put("message", "回调注册服务状态正常");
        return ResponseEntity.ok(response);
    }

    /**
     * 清理所有回调
     */
    @PostMapping("/clear-callbacks")
    public ResponseEntity<Map<String, Object>> clearCallbacks() {
        Map<String, Object> response = new HashMap<>();
        try {
            callbackRegistryService.clearAllCallbacks();
            response.put("success", true);
            response.put("message", "所有回调已清理");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("清理回调失败", e);
            response.put("success", false);
            response.put("message", "清理回调失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 订阅主题
     */
    @PostMapping("/subscribe/{topicName}")
    public ResponseEntity<Map<String, Object>> subscribeTopic(@PathVariable String topicName) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = zrddsManagerService.subscribeTopic(topicName);
            response.put("success", success);
            response.put("message", success ? "主题订阅成功" : "主题订阅失败");
            response.put("topicName", topicName);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("订阅主题失败: {}", topicName, e);
            response.put("success", false);
            response.put("message", "订阅主题失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 取消订阅主题
     */
    @PostMapping("/unsubscribe/{topicName}")
    public ResponseEntity<Map<String, Object>> unsubscribeTopic(@PathVariable String topicName) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = zrddsManagerService.unsubscribeTopic(topicName);
            response.put("success", success);
            response.put("message", success ? "主题取消订阅成功" : "主题取消订阅失败");
            response.put("topicName", topicName);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("取消订阅主题失败: {}", topicName, e);
            response.put("success", false);
            response.put("message", "取消订阅主题失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 发布测试数据
     */
    @PostMapping("/publish-test")
    public ResponseEntity<Map<String, Object>> publishTestData(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String topicName = (String) request.get("topicName");
            String message = (String) request.get("message");

            if (topicName == null || message == null) {
                response.put("success", false);
                response.put("message", "缺少必要参数：topicName 和 message");
                return ResponseEntity.ok(response);
            }

            boolean success = zrddsManagerService.publishData(topicName, message);
            response.put("success", success);
            response.put("message", success ? "测试数据发布成功" : "测试数据发布失败");
            response.put("topicName", topicName);
            response.put("data", message);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发布测试数据失败", e);
            response.put("success", false);
            response.put("message", "发布测试数据失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取ZRDDS配置信息
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getZRDDSConfig() {
        Map<String, Object> response = new HashMap<>();
        try {
            response.put("success", true);
            response.put("zrddsType", "真实ZRDDS中间件");
            response.put("description", "使用ZRDDS的真实API进行数据传输，支持高吞吐量和低延迟");
            response.put("features", new String[] {
                    "真实中间件集成",
                    "支持多种传输协议",
                    "QoS配置支持",
                    "自动主题发现",
                    "高可靠性传输"
            });
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取ZRDDS配置失败", e);
            response.put("success", false);
            response.put("message", "获取配置失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean initialized = zrddsManagerService.isInitialized();
            response.put("success", true);
            response.put("status", initialized ? "healthy" : "unhealthy");
            response.put("zrdds", initialized ? "running" : "stopped");
            response.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("健康检查失败", e);
            response.put("success", false);
            response.put("status", "error");
            response.put("message", e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}
